package com.atguigu.tingshu.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.sound.midi.Track;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	RabbitService rabbitService;


	@Override
	public BigDecimal getTrackBreakSecond(Long trackId, Long userId) {
		//组成集合名称
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		//从集合中获取对应的播放时长
		Query query = Query.query(Criteria.where("trackId").is(trackId));
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//判断
		if (null != userListenProcess){
			return userListenProcess.getBreakSecond();
		}
		return new BigDecimal(0.00);
	}


	@Override
	public void updateListenProcess(UserListenProcessVo userListenProcessVo, Long userId) {
		//先查出MongoDB中是否有该声音
		//组成集合名
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		//从集合中获取对应的播放时常
		Query query = Query.query(Criteria.where("trackId").is(userListenProcessVo.getTrackId()));
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//判断
		if (null != userListenProcess){
			//覆盖写声音播放的进度
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			userListenProcess.setUpdateTime(new Date());
		}else{
			//新增播放进度
			 userListenProcess = new UserListenProcess();
			userListenProcess.setUserId(userId);
			userListenProcess.setTrackId(userListenProcessVo.getTrackId());
			userListenProcess.setAlbumId(userListenProcessVo.getAlbumId());
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			userListenProcess.setCreateTime(new Date());
			userListenProcess.setUpdateTime(new Date());
		}
		//保存数据
		this.mongoTemplate.save(userListenProcess,collectionName);
		//利用分布式锁的思想解决声音重复播放的问题，不解决会造成恶意刷单
		String key = userId+":"+userListenProcess.getTrackId();
		Boolean result = this.redisTemplate.opsForValue().setIfAbsent(key, "1", 24, TimeUnit.HOURS);
		//判断当前结果
		if (result){
			//说明这个用户是第一次播放
			TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
			trackStatMqVo.setCount(1);
			trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
			trackStatMqVo.setTrackId(userListenProcess.getTrackId());
			trackStatMqVo.setAlbumId(userListenProcess.getAlbumId());
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			trackStatMqVo.setBusinessNo(uuid);
			rabbitService.sendMessage(MqConst.EXCHANGE_TRACK,MqConst.ROUTING_TRACK_STAT_UPDATE, JSON.toJSONString(trackStatMqVo));
		}
	}

	@Override
	public Map<String, Object> getLatelyTrack(Long userId) {
		//创建map集合
		HashMap<String, Object> map = new HashMap<>();
		//数据存储在mongoDB
		//获取集合名称
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		//设置查询条件
		Query query = new Query();
		query.with(Sort.by(Sort.Direction.DESC,"updateTime")).limit(1);
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//判断
		if (null != userListenProcess){
			map.put("albumId",userListenProcess.getAlbumId());
			map.put("trackId",userListenProcess.getTrackId());
		}
		return map;
	}
}
